<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.username" clearable class="filter-item" style="width: 200px;" placeholder="请输入管理员名称" />
      <el-button v-permission="['GET /admin/admin/list']" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button v-permission="['POST /admin/admin/create']" class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
      <!-- <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button> -->
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。"   fit highlight-current-row>
      <el-table-column align="center" label="GMID" prop="id" sortable >
        <template slot-scope="scope">
          {{scope.row.user.id}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="头像" prop="avatar">
        <template slot-scope="scope">
          <img v-if="scope.row.user.avatar" :src="scope.row.user.avatar" width="40">
        </template>
      </el-table-column>
      <el-table-column align="center" label="用户名" prop="username" >
        <template slot-scope="scope">
          {{scope.row.user.username}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="昵称" prop="nickname" >
        <template slot-scope="scope">
          {{scope.row.user.nickname}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="等级" prop="userLevel" >
        <template slot-scope="scope">
          {{scope.row.user.userLevel}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="手机号" prop="mobile" >
        <template slot-scope="scope">
          {{scope.row.user.mobile}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="微信openID" prop="weixinOpenid" >
        <template slot-scope="scope">
          {{scope.row.user.weixinOpenid}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="账号余额" prop="balancePrice" sortable>
        <template slot-scope="scope">
          {{scope.row.user.balancePrice}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="易宝阁费率" >
        <template slot-scope="scope">
          {{scope.row.boxgameconfig.ybgRate}}%
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-permission="['POST /admin/admin/update']" type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button v-permission="['POST /admin/admin/delete']" type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="dataForm.user" status-icon label-position="left" label-width="120px"  >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="dataForm.user.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="dataForm.user.password"  auto-complete="off" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="dataForm.user.mobile" type="mobile" auto-complete="off" />
        </el-form-item>

        <el-form-item label="头像" prop="avatar">
          <el-upload :data='{dirName:""}' :headers="headers" :action="uploadPath" :show-file-list="false" :on-success="uploadAvatar" class="avatar-uploader" accept=".jpg,.jpeg,.png,.gif">
            <img v-if="dataForm.user.avatar" :src="dataForm.user.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>

          <h3>店铺相关设置</h3>
          <el-form-item label="易宝阁费率：">
            <el-input-number  v-model="dataForm.boxgameconfig.ybgRate" :min="1" :max="99" />% 易宝阁官方收取的费率，用于服务器维护支撑
        </el-form-item>
        <el-form-item label="店铺费率：">
          <el-input-number  v-model="dataForm.boxgameconfig.shopRate"   :min="1" :max="99" />% GM可自行设置交易手续费，相关收益金额直接到达店铺余额，订单明细可以查看费率明细
        </el-form-item>
        <el-form-item label="店铺承担费率：">
          <el-input-number  v-model="dataForm.boxgameconfig.shopBearRate" :min="1" :max="99"   />% 设置店铺承担的费率比例，如不承担设置0
        </el-form-item>
        <el-form-item label="卖家承担费率：">
          <el-input-number  v-model="dataForm.boxgameconfig.sellerBearRate" :min="1" :max="99"   />% 设置卖家承担的费率比例，如不承担设置0
        </el-form-item>
        <el-form-item label="买家承担费率：">
          <el-input-number  v-model="dataForm.boxgameconfig.buyer"  :min="1" :max="99"  />% 设置卖家承担的费率比例，如不承担设置0
        </el-form-item>
        <!-- <h5 v-if="totleRate">易宝阁费率+店铺费率=买家承担费率+卖家承担费率  必须持平否</h5> -->
        <!-- ps：易宝阁费率+店铺费率=买家承担费率+卖家承担费率  必须持平否则不对，提示正确设置 -->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
</style>

<script>
import { listAdmin, createAdmin, updateAdmin, deleteAdmin } from '@/api/consUser'
import { roleOptions } from '@/api/role'
import { uploadPath } from '@/api/storage'
import { getToken } from '@/utils/auth'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

export default {
  name: 'Admin',
  components: { Pagination },
  data() {
    return {
      uploadPath,
      list:[],
      total: 0,
      roleOptions: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        usertype:1
      },
      dataForm: {
        user:{
          id: '',
          username: '',
          password: '',
          avatar: '',
          mobile:'',
          userType:1,
          gender:0,lastLoginIp:'0.0.0.0',nickname:'',sessionKey:'',status:0,
        },
        boxgameconfig:{
          ybgRate: 1,//易宝阁费率
          shopRate: 1,//店铺费率
          shopBearRate: 1,//店铺承担费率
          sellerBearRate: 1,//，卖家承担费率
          buyer:1,//买家承担费率
        },
        
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        username: [
          { required: true, message: '管理员名称不能为空', trigger: 'blur' }
        ],
        password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
        mobile: [{ required: true, message: '手机号不能为空', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  computed: {
    headers() {
      return {
        'X-Hyxxkj-Admin-Token': getToken()
      }
    }
  },
  created() {
    this.getList()

    roleOptions().then((response) => {
      this.roleOptions = response.data.data.list
    })
  },
  methods: {
    formatRole(roleId) {
      for (let i = 0; i < this.roleOptions.length; i++) {
        if (roleId === this.roleOptions[i].value) {
          return this.roleOptions[i].label
        }
      }
      return ''
    },
    getList() {
      this.listLoading = true
      listAdmin(this.listQuery)
        .then((response) => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
  
    uploadAvatar: function(response) {
      this.dataForm.avatar = response.data.url
    },
    handleCreate() {

      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      // this.$nextTick(() => {
      //   this.$refs['dataForm'].clearValidate()
      // })
    },
    totleRate(){
      return this.dataForm.boxgameconfig.ybgRate+this.dataForm.boxgameconfig.shopRate==this.dataForm.boxgameconfig.sellerBearRate+this.dataForm.boxgameconfig.buyer+this.dataForm.boxgameconfig.shopBearRate
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if(!this.totleRate()){
            this.$notify({
              title: '警告',
              message: '易宝阁费率+店铺费率=店铺承担费率+买家承担费率+卖家承担费率 必须持平否',
              type: 'warning',
             // duration: 0
            });
    
            return false
          }else{
          this.dataForm.user.weixinOpenid=this.dataForm.user.mobile
          this.dataForm.user.nickname=this.dataForm.user.username
          this.dataForm.user.sessionKey=this.dataForm.user.mobile
          createAdmin(this.dataForm)
            .then((response) => {
              this.dialogFormVisible = false
              this.getList()
              this.$notify.success({
                title: '成功',
                message: '添加GM用户成功'
              })
            })
            .catch((response) => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
          }
        }
      })
    },
    handleUpdate(row) {
      this.dataForm=row
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if(!this.totleRate()){
            this.$notify({
              title: '警告',
              message: '易宝阁费率+店铺费率=买家承担费率+卖家承担费率 必须持平否',
              type: 'warning',
             // duration: 0
            });
    
            return false
          }else{
          updateAdmin(this.dataForm)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.dataForm.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新GM用户成功'
              })
            })
            .catch((response) => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
          }
        }
      })
    },
    handleDelete(row) {
      row.deleted=true
      updateAdmin(row)
            .then(() => {
              this.getList()
              this.$notify.success({
                title: '成功',
                message: '删除GM用户成功'
              })
            })
            .catch((response) => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then((excel) => {
        const tHeader = ['管理员ID', '管理员名称', '管理员头像']
        const filterVal = ['id', 'username', 'avatar']
        excel.export_json_to_excel2(tHeader, this.list, filterVal, '管理员信息')
        this.downloadLoading = false
      })
    }
  }
}
</script>
